//
//  QRCodeViewController.m
//  Weiweiyunshi
//
//  Created by 王译 on 17/2/5.
//  Copyright © 2017年 王译. All rights reserved.
//

#import "QRCodeViewController.h"
#import "SGScanningQRCodeView.h"
#import "SGQRCodeTool.h"
#import "SGAlertView.h"
#import <Photos/Photos.h>
#import "ResultViewController.h"
@interface QRCodeViewController ()<AVCaptureMetadataOutputObjectsDelegate>
{
    SGScanningQRCodeView *scanView;
    AVCaptureSession *session;
    AVCaptureVideoPreviewLayer *previewLayer;
    ResultViewController *resultVC;
}
@end

@implementation QRCodeViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"二维码";
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"header_back_icon"] style:UIBarButtonItemStyleDone target:self action:@selector(pop)];
    self.navigationItem.leftBarButtonItem = backItem;
    // Do any additional setup after loading the view.
}
-(void)pop
{
    [self.navigationController popViewControllerAnimated:YES];
    
}
-(void)viewWillAppear:(BOOL)animated{
    scanView = [[SGScanningQRCodeView alloc] initWithFrame:self.view.frame outsideViewLayer:self.view.layer];
    [self.view addSubview:scanView];
    
    session = [[AVCaptureSession alloc] init];
    // 实例化预览图层, 传递_session是为了告诉图层将来显示什么内容
    previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:session];
    [SGQRCodeTool SG_scanningQRCodeOutsideVC:self session:session previewLayer:previewLayer];
}


- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    
    [session stopRunning];
    
    // 2、删除预览图层
    [previewLayer removeFromSuperlayer];
    
    // 3、设置界面显示扫描结果
    if (metadataObjects.count > 0) {
        AVMetadataMachineReadableCodeObject *obj = metadataObjects[0];
        NSLog(@"metadataObjects = %@", metadataObjects);
        NSLog(@"stringValue = = %@", obj.stringValue);
        resultVC = [[ResultViewController alloc]init];
        resultVC.userId = obj.stringValue;
        [self.navigationController pushViewController:resultVC animated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
